package com.lry.event;

import com.lry.registy.URL;
import com.lry.util.CollectionUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class RpcListenerLoader {

    static List<RpcListener> listenerList = new ArrayList<>();
    static {
        listenerList.add(new ProviderChangeListener());
        listenerList.add(new NodeChangeListener());

    }

    public static void sendEvent(RpcEvent event) {
        if (CollectionUtils.isEmpty(listenerList)) {
            return;
        }
        for (RpcListener rpcListener : listenerList) {
            Class<?> type = getInterfaceT(rpcListener);
            if (type.equals(event.getClass())) {
                try {
                    rpcListener.callback(event);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void sendAsyncEvent(RpcEvent event) {
        CompletableFuture.runAsync(()->{
            sendEvent(event);
        });
    }

    public static Class<?> getInterfaceT(Object o) {
        Type[] types = o.getClass().getGenericInterfaces();
        ParameterizedType parameterizedType = (ParameterizedType) types[0];
        Type type = parameterizedType.getActualTypeArguments()[0];
        if (type instanceof Class<?>) {
            return (Class<?>) type;
        }
        return null;
    }

}
